package cn.xuexiluxian.open.framework.security.handler;

import cn.xuexiluxian.open.common.enums.ResultStatusCodeEnum;
import cn.xuexiluxian.open.common.response.ResponseResult;
import cn.xuexiluxian.open.framework.security.exception.KaptchaExpiredException;
import cn.xuexiluxian.open.framework.security.exception.KaptchaValidateException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component("customAuthenticationFailureHandler")
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        ResponseResult<String> result;
        if (e instanceof BadCredentialsException) {
            result = ResponseResult.error(ResultStatusCodeEnum.USERNAME_PASSWORD_ERROR);
        } else if (e instanceof DisabledException) {
            result = ResponseResult.error(ResultStatusCodeEnum.USER_STATUS_DISABLE);
        } else if (e instanceof UsernameNotFoundException) {
            result = ResponseResult.error(ResultStatusCodeEnum.USER_NOT_EXIST.getCode(), e.getMessage());
        } else if (e instanceof KaptchaValidateException) {
            result = ResponseResult.error(ResultStatusCodeEnum.CAPTCHA_ERROR);
        } else if (e instanceof KaptchaExpiredException) {
            result = ResponseResult.error(ResultStatusCodeEnum.CAPTCHA_EXPIRED);
        } else {
            result = ResponseResult.error(ResultStatusCodeEnum.USER_LOGIN_ERROR);
        }

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(result));
    }
}
